const MongoClient = require('mongodb').MongoClient;
let ObjectId = require('mongodb').ObjectId;


let baseData = () => new Promise((resolve, reject) => {
    const client = new MongoClient('mongodb://localhost:27017', { useNewUrlParser: true });
    client.connect(function(err) {
        if (err) {
            reject(err);
        }
        console.log("Connected successfully to server");
        const db = client.db('student');
        resolve(db)
    });
    client.close();
})

exports.findDB = async() => {
    let tmp = await baseData();
    let collection = tmp.collection('demo'); //链接数据表
    return new Promise((resolve, reject) => {
        collection.find({}).toArray(function(err, docs) {
            if (err) {
                reject(err)
            }
            resolve(docs)
        });
    })
}


exports.addDB = async(data) => {
    let tmp = await baseData();
    let collection = tmp.collection('demo'); //链接数据表
    return new Promise((resolve, reject) => {
        collection.insertMany([data], function(err, result) {
            if (err) {
                reject(err)
            }
            resolve(result)
        });
    })
}


exports.delDB = async(data) => {
    let tmp = await baseData();
    let collection = tmp.collection('demo'); //链接数据表
    return new Promise((resolve, reject) => {
        collection.deleteOne({ _id: ObjectId(data.id) }, function(err, result) {
            if (err) {
                reject(err)
            }
            resolve(result)
        });
    })
}

exports.updateDB = async(data) => {

    let tmp = await baseData();
    let collection = tmp.collection('demo'); //链接数据表
    return new Promise((resolve, reject) => {
        collection.updateMany({ "_id": ObjectId(data.id) }, { $set: { username: data.username, age: data.age, register: data.register, telephone: data.telephone, email: data.email, enData: data.enData } }, function(err, result) {
            if (err) {
                reject(err)
            }
            resolve(result)
        });
    })
}